package com.qf.shopping.ustils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class IBatisUtils {

    private static Reader reader=null;   //这个是用来加载配置文件的

    private static SqlSessionFactory sqlSessionFactory=null;

    private static ThreadLocal<SqlSession> threadLocal=null;

    static{
        try {
            reader= Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
            threadLocal=new ThreadLocal<SqlSession>();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取这个会话对象
     * @return
     */
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(null!=sqlSession){  //说民在当前方法中已经执行过了
             return sqlSession;
        }
        sqlSession=sqlSessionFactory.openSession();
        threadLocal.set(sqlSession);
        return sqlSession;
    }


    /**
     * 关闭的资源
     */
    public static void close(){
        SqlSession sqlSession = threadLocal.get();
        if(null!=sqlSession){
            sqlSession.commit();
            sqlSession.close();
            threadLocal.remove();
        }
    }


}
